<template>
    <div v-loading="loading" class="console-page">
        <el-form inline :model="searchForm" class="e-page form-item form-auto-resize" spellcheck="false"
            @submit.native.prevent>
            <el-row class="toolbar" ref="el">
                <el-col :span="4" style="padding-right: 5px">
                    <el-input v-model="searchForm.appName" placeholder="执行器名称" clearable class="input-auto-resize" />
                </el-col>
                <el-col :span="4" style="padding-right: 5px">
                    <el-input v-model="searchForm.title" placeholder="组名称" clearable class="input-auto-resize" />
                </el-col>
                <el-col :span="4" style="padding-right: 5px">
                    <el-button type="primary" @click="getAgentData" circle :icon="getIcon('search')"
                        :loading="bt_loading" class="button-auto-resize" native-type="submit" />
                </el-col>
                <el-col :span="12" style="text-align: right" v-permission="$permission.Write">
                    <el-button :icon="getIcon('plus')" circle class="button-auto-resize" @click="editAgent(null)" />
                    <el-button :icon="getIcon('grid')" circle class="button-auto-resize" @click="listAgent" />
                </el-col>
            </el-row>
        </el-form>
        <el-row class="agent" style="height:calc(100% - var(--font-size) * 2 - 10px)">
            <el-scrollbar style="height: 100%;width: 100%;">
                <div v-if="tableData.length === 0">
                    <div style="width:50%;display:block;margin:10% auto 0 auto;text-align: center">
                        无数据
                    </div>
                </div>
                <div v-else>
                    <el-row>
                        <el-col :span="6" v-for="(agentInfo, index) in tableData" :key="index" style="padding:0 3px;">
                            <el-card :body-style="{ padding: '0px' }" shadow="hover"
                                style="margin-bottom:10px;min-width: 220px">
                                <template #header>
                                    <div class="e-page agent-header">
                                        <el-row>
                                            <el-col :span="20">
                                                <span class="font-auto-resize">{{ agentInfo.appName }}</span>
                                            </el-col>
                                            <el-col :span="4" v-permission="$permission.Delete">
                                                <div class="agent-delete">
                                                    <el-button link :icon="getIcon('delete')"
                                                        @click="deleteAgent(agentInfo)" class="button-auto-resize"
                                                        confirm-title="是否确认删除该执行器组?" />
                                                </div>
                                            </el-col>
                                        </el-row>
                                    </div>
                                </template>
                                <el-form :model="agentInfo" status-icon ref="agentInfoRef" spellcheck="false"
                                    class="form-auto-resize form-auto-resize" @submit.native.prevent>
                                    <el-form-item label="名称" prop="title"
                                        style="padding-bottom: 5px;padding-top: 3px;text-align: center">
                                        <span style="cursor: default;width: 100%;" class="cursor-default">
                                            {{ agentInfo.title }}
                                        </span>
                                    </el-form-item>
                                    <el-form-item label="注册方式" prop="status"
                                        style="padding-bottom: 5px;padding-top: 3px">
                                        <el-tag :type="agentInfo.status === 0 ? 'info' : 'primary'" disable-transitions
                                            class="input-auto-resize register-tag">
                                            {{ agentInfo.addressType === 0 ? '自动' : '手动' }}
                                        </el-tag>
                                    </el-form-item>
                                    <el-form-item label="机器地址" prop="host"
                                        style="padding-bottom: 5px;padding-top: 3px;text-align: center">
                                        <span style="cursor: pointer;color: #409EFF;width: 100%" class="cursor-pointer"
                                            @click="editAgent(agentInfo)">{{
                                                "查看(" + (agentInfo.registryList && agentInfo.registryList.length > 0 ?
                                                    agentInfo.registryList.length
                                                    : 0) + ")"
                                            }}</span>
                                    </el-form-item>
                                </el-form>
                            </el-card>
                        </el-col>
                    </el-row>
                </div>
            </el-scrollbar>
        </el-row>

        <el-dialog :title="curAgentInfo.dialogTitle" v-model="dialog" width="50%" :show-close="false" @closed="close"
            :close-on-click-modal="curAgentInfo.dialogTitle === '编辑执行器'" append-to-body class="agent-dialog"
            :close-on-press-escape="curAgentInfo.dialogTitle === '编辑执行器'">
            <el-form :model="curAgentInfo" status-icon ref="curAgentInfoRef" class="form-auto-resize" spellcheck="false"
                :rules="rules" :validate-on-rule-change="false" inline @submit.native.prevent>
                <el-form-item label="AppName" prop="appName" style="padding-bottom: 5px;padding-top: 3px">
                    <el-input class="input-auto-resize" v-model="curAgentInfo.appName" />
                </el-form-item>
                <el-form-item label="名称" prop="title" style="padding-bottom: 5px;padding-top: 3px">
                    <el-input class="input-auto-resize" v-model="curAgentInfo.title" />
                </el-form-item>
                <el-form-item label="注册方式" prop="addressType" style="padding-bottom: 5px;padding-top: 3px">
                    <el-radio v-model="curAgentInfo.addressType" :label="0">自动注册</el-radio>
                    <el-radio v-model="curAgentInfo.addressType" :label="1">手动注册</el-radio>
                </el-form-item>
                <el-form-item class="last" label="机器地址" prop="addressList" style="padding-top: 3px">
                    <div class="el-textarea el-input" v-show="curAgentInfo.addressType === 0">
                        <p class="el-textarea__inner">{{ curAgentInfo.addressList }}</p>
                    </div>
                    <el-input class="font-auto-resize" v-model="curAgentInfo.addressList" type="textarea" resize="none"
                        rows="5" v-show="curAgentInfo.addressType === 1" placeholder="请输入执行器地址列表，多地址逗号分隔" />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialog = false" :icon="getIcon('close')" class="button-auto-resize" circle />
                    <el-button type="primary" @click="modifyAgent" :icon="getIcon('check')" class="button-auto-resize"
                        circle v-permission="$permission.Update" />
                </div>
            </template>
        </el-dialog>

        <el-drawer :show-close="false" :with-header="false" size="410px" v-model="agentListDrawer" direction="rtl"
            class="agent-drawer forbid-select" @open="useModalSize(true)" @closed="useModalSize(false)" append-to-body>
            <div v-for="(item, index) in agentList" :key="index" class="agent-content">
                <div class="agent-item">
                    <span class="agent-item-title">执行器ID</span>
                    <span class="agent-item-content">{{ item.id }}</span>
                </div>
                <div class="agent-item">
                    <span class="agent-item-title">执行器组别</span>
                    <span class="agent-item-content">{{ item.registryKey }}</span>
                </div>
                <div class="agent-item">
                    <span class="agent-item-title">执行器地址</span>
                    <span class="agent-item-content">{{ item.registryValue }}</span>
                </div>
                <div class="agent-item">
                    <span class="agent-item-title">心跳时间</span>
                    <span class="agent-item-content">{{ item.updateTime }}</span>
                    <span style="padding-left: 5px;color: red">
                        {{ Math.max((new Date().getTime() - new Date(item.updateTime).getTime()) / 1000, 0) }}秒前
                    </span>
                </div>
            </div>
        </el-drawer>
    </div>
</template>
<script setup>
import { getIcon } from "@/utils/tools"
import { useElMessage, useModalSize, useRequest } from "@usehook"

let tableData = $ref([])
let loading = $ref(false)
let dialog = $ref(false)
let searchForm = $ref({ "appName": "", "title": "" })
let bt_loading = $ref(false)
let agentList = $ref([])
let agentListDrawer = $ref(false)
let curAgentInfo = $ref({
    addressList: "",
    addressType: 0,
    appName: "",
    registryList: [],
    title: "",
    id: null,
    dialogTitle: ""
})

const checkAppName = (_rule, value, cb) => {
    //验证手机号的正则表达式
    const name = /^[a-z][a-z0-9-]{3,63}$/
    if (name.test(value)) {
        return cb()
    }
    cb(new Error('以小写字母开头，由小写字母、数字和中划线组成，长度4~64之间'))
}

let rules = $ref({
    appName: [
        { required: true, message: '请输入AppName', trigger: 'blur' },
        { validator: checkAppName, trigger: "blur" }
    ],
    title: [
        { required: true, message: '请输入title', trigger: 'blur' },
        { min: 4, max: 12, message: '长度在4~12之间', trigger: 'blur' }
    ]
})

const editAgent = (agentInfo) => {
    useModalSize()
    if (agentInfo) {
        curAgentInfo.addressList = agentInfo.addressList;
        curAgentInfo.addressType = agentInfo.addressType;
        curAgentInfo.appName = agentInfo.appName;
        curAgentInfo.registryList = agentInfo.registryList;
        curAgentInfo.title = agentInfo.title;
        curAgentInfo.id = agentInfo.id;
        curAgentInfo.dialogTitle = "编辑执行器组"
    } else {
        curAgentInfo.dialogTitle = "新增执行器组"
    }
    dialog = true
}

const listAgent = () => {
    useRequest("/jobgroup/getRegistry").then(resp => {
        if (resp && resp.status) {
            agentList = resp.data
        }
    })
    agentListDrawer = true
}

const curAgentInfoRef = $ref(null)
const close = () => {
    useModalSize(false)
    curAgentInfoRef.clearValidate();
    curAgentInfo = {
        addressList: "",
        addressType: 0,
        appName: "",
        registryList: [],
        title: "",
        id: null,
        dialogTitle: ""
    }
}

const deleteAgent = (agent) => {
    useRequest({ url: "/jobgroup/remove", id: agent.id, method: "post" }).then(resData => {
        if (resData && resData.status) {
            useElMessage("删除成功");
            getAgentData();
        } else if (resData && !resData.status) {
            if (resData.message) useElMessage.error(resData.message)
        } else {
            useElMessage("删除失败")
        }
    })
}

const modifyAgent = () => {
    curAgentInfoRef.validate((valid) => {
        if (valid) {
            useRequest({ url: curAgentInfo.id === null ? "/jobgroup/save" : "/jobgroup/update", method: "post", ...curAgentInfo }).then(resData => {
                if (resData) {
                    if (resData.status) { //0表示成功，1表示失败
                        useElMessage("修改成功");
                        getAgentData()
                        dialog = false
                    } else {
                        if (resData.message) useElMessage.error(resData.message)
                    }
                }
            })
        }
    });
}

const getAgentData = () => {
    loading = true
    bt_loading = true
    useRequest('/jobgroup/getPageData', searchForm).then(resp => {
        if (resp) {
            tableData = resp.data
        }
    }).finally(_ => {
        loading = false
        bt_loading = false
    })
}

watch(() => curAgentInfo.addressType, (newVal) => {
    if (newVal === 1) {
        rules = {
            appName: [
                { required: true, message: '请输入AppName', trigger: 'blur' },
                { validator: checkAppName, trigger: "blur" }
            ],
            title: [
                { required: true, message: '请输入title', trigger: 'blur' },
                { min: 4, max: 12, message: '长度在4~12之间', trigger: 'blur' }
            ],
            addressList: [
                { required: true, message: '手动录入注册方式，机器地址不可为空', trigger: 'blur' },
            ]
        }
    } else {
        rules = {
            appName: [
                { required: true, message: '请输入AppName', trigger: 'blur' },
                { validator: checkAppName, trigger: "blur" }
            ],
            title: [
                { required: true, message: '请输入title', trigger: 'blur' },
                { min: 4, max: 12, message: '长度在4~12之间', trigger: 'blur' }
            ]
        }
        curAgentInfoRef.clearValidate('addressList');
    }
})

onMounted(() => {
    getAgentData()
})
</script>

<style scoped>
:deep(.agent .el-card__header) {
    padding: 6px 10px;
}

:deep(.agent .el-form-item__label) {
    text-align: left;
    padding-left: 10px
}

:deep(.el-input.is-disabled .el-input__inner) {
    cursor: default;
    color: #323229;
    background-color: #FFF
}

:deep(.el-scrollbar__wrap) {
    overflow-x: hidden;
}

:deep(.el-form-item__error) {
    top: 26%;
    right: 40px;
    left: unset;
    font-size: calc(var(--font-size) - 4px);
    pointer-events: none;
}

:deep(.last .el-form-item__error) {
    top: 2%;
    right: 5px;
}

:deep(.el-loading-mask) {
    border-radius: 5px;
    border-bottom: none;
    border-right: none;
}

.ace_editor {
    margin: 5px 0 !important;
}

:deep(.el-scrollbar__bar.is-vertical > div) {
    width: 0 !important;
}

:deep(p) {
    margin: 0;
    background: rgb(238, 238, 238);
}

:deep(.el-textarea__inner) {
    height: 110px;
}

:deep(.agent-header) {
    white-space: nowrap;
    height: 100%;
}

:deep(.agent-delete) {
    text-align: right;
}

:deep(.register-tag) {
    padding: 0 45px;
    text-align: center;
    background: rgb(236 245 255 / 20%);
    border-color: rgb(217 236 255 / 10%);
}
</style>

<style>
.agent-dialog.el-dialog .el-dialog__header {
    border-bottom: 1px solid #e4e7ec;
    padding: 20px 15px;
}

.agent-dialog.el-dialog .el-dialog__body .el-form-item {
    margin-bottom: 5px
}

.agent-dialog.el-dialog .el-dialog__body {
    padding: 7px !important;
}

.agent-dialog.el-dialog .el-dialog__footer {
    padding: 10px;
    border-top: 1px solid #e4e7ec;
}

.agent-drawer .agent-content {
    padding: 5px;
    background: fixed rgba(0, 0, 0, 0.05);
}

.agent-drawer .agent-content+.agent-content {
    margin-top: 5px;
}

.agent-drawer .agent-item+.agent-item {
    padding-top: 5px;
}

.agent-drawer .agent-item-title {
    width: calc(var(--font-size) * 5 + 8px);
    display: inline-block;
    text-align: right;
    padding-right: 5px;
}
</style>